from flask import request, json
from gamebox.exceptions import ApiKeyDefinedError
from gamebox import response, errorcodes
from json import JSONDecodeError
import urllib.parse
import gamebox.api.account
import gamebox.api.user

_api_list = {}


def register(method, fn):
    if _api_list.__contains__(method):
        raise ApiKeyDefinedError
    _api_list[method] = fn


def api_request_process():
    '''
    API 请求处理
    :return:
    '''
    try:
        method = request.form.get('m')
        if not method:
            return response.result(errorcodes.UNSUPPORTED_METHOD)
        if not _api_list.__contains__(method):
            return response.result(errorcodes.UNSUPPORTED_METHOD)
        params = request.form.get('d')
        fn = _api_list.get(method)
        if params:
            params = urllib.parse.unquote(params, 'utf-8')
            params = json.loads(params)
        result = fn(params)
        if result:
            return result
        return response.result(errorcodes.SUCCESS)
    except JSONDecodeError:
        return response.result(errorcodes.PARAMETER_INVALID)
    except Exception as e:
        return response.result(errorcodes.UNKNOWN_ERROR, error=str(e))


# 注册对外方法名,并绑定对应的方法
register('account.login', account.login)
register('account.refresh', account.refresh_token)
register('account.logout', account.logout)
register('user.add', user.add_user)
register('user.update', user.update_user)
register('user.delete', user.delete_user)
